<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;


use AlibabaCloud\SDK\Imm\V20200930\Imm;
use AlibabaCloud\SDK\Imm\V20200930\Models\CreateProjectRequest;
use AlibabaCloud\SDK\Imm\V20200930\Models\DetectImageFacesRequest;
use AlibabaCloud\SDK\Imm\V20200930\Models\GetProjectRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\BaseController;
use app\common\service\AgentApiService;
use OSS\OssClient;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureAvatar;
use app\common\service\ApiService;
use app\admin\model\FigureCloneSet;
use FFMpeg\FFMpeg;

/**
 * 形象克隆操作
 *
 * @author Administrator
 *
 */
class Avatar extends BaseController
{

    /**
     * 克隆设置
     * http://aigc.weijuyunke.cn/mobile/avatar/cloneSet
     */
    public function cloneSet()
    {
        $set = FigureCloneSet::where("id", 1)->find();

        if (empty($set)) {
            $set = [];
        }

        if (!empty($set['protocol'])) {
            $set['protocol'] = htmlspecialchars_decode($set['protocol']);
        }

        if (!empty($set['quick_clone_notice'])) {
            $set['quick_clone_notice'] = htmlspecialchars_decode($set['quick_clone_notice']);
        }

        if (!empty($set['avatar_clone_notice'])) {
            $set['avatar_clone_notice'] = htmlspecialchars_decode($set['avatar_clone_notice']);
        }

        if (!empty($set['video_notice'])) {
            $set['video_notice'] = htmlspecialchars_decode($set['video_notice']);
        }

        if (!empty($set['voice_notice'])) {
            $set['voice_notice'] = htmlspecialchars_decode($set['voice_notice']);
        }

        if (!empty($set['voice_high_notice'])) {
            $set['voice_high_notice'] = htmlspecialchars_decode($set['voice_high_notice']);
        }

        if (!empty($set['composite_notice'])) {
            $set['composite_notice'] = htmlspecialchars_decode($set['composite_notice']);
        }

        return result(0, 'success', $set);
    }

    /**
     * 形象开始训练
     * http://aigc.weijuyunke.cn/mobile/avatar/startTraining
     *
     * @param
     *            uid 用户id
     * @param
     *            name 名称
     * @param
     *            a_type 1-形象 2-照片
     * @param
     *            video_url 视频链接
     * @param
     *            image_url 图片链接
     * @param
     *            video_backgroud_image 背景图片链接
     * @param
     *            video_backgroud_color 背景颜色
     */
    public function startTraining()
    {
        try {
            $uid = input('uid');
            $id = input('id');
            $set = FigureCloneSet::where("id", 1)->find();
            if ($set['avatar_high_open'] != 1) {
                return result(0, '线路关闭');
            }
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $video_url = input('video_url');
            if (empty($video_url)) {
                return result(-1, 'video_url必传');
            }
            $log_no = getPayNo('AT');
            $data = array(
                'log_no' => $log_no,
                'uid' => $uid,
                'a_type' => 1,
                'type' => 1,
                'is_avatar' => input('is_avatar')
            );
            $data['name'] = !empty(input('name')) ? input('name') : date('ymd') . rand(999, 9999);
            if (!empty($video_url)) {

                $data['video_url'] = $video_url;
                $upload = sysconfig('upload');

                if ($upload['upload_type'] == 'alioss') {
                    $data['video_cover'] = $video_url . "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto";
                } elseif ($upload['upload_type'] == 'txcos') {
                    $data['video_cover'] = $video_url . "?ci-process=snapshot&time=0.01";
                } elseif ($upload['upload_type'] == 'qnoss') {
                    $data['video_cover'] = $video_url . "?vframe/jpg/offset/0";
                }
            }

            $is_avatar = input('is_avatar');
            if ($is_avatar && $is_avatar == 1) {// 分身数据不需要审核

                if (!$user['is_member']) {
                    $tally = sysconfig('tally', 'avatar_high_deduct');
                    if ($user['balance'] < $tally) {
                        return result(-2, '点数不足，请充值');
                    }
                }
                $params = [
                    'name' => $data['name'],
                    'video_url' => $video_url
                ];
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                    $result = $apiService->avatarStartTraining($params);
                } else {
                    $apiService = new ApiService();
                    $result = $apiService->avatarStartTraining($params);
                }

                if (isset($result['code']) && $result['code'] == 1) {
                    $avatar = new FigureAvatar();
                    $avatar->save($data);
                    user_balance_used($uid, $log_no, 2, 40);
                    $data = $result['data'];
                    $avatar->save([
                        '_id' => $data['id'],
                        'current_status' => $data['current_status']
                    ]);
                    return result(0, '上传成功', $avatar);
                } else {
                    return result(-1, $result['msg']);
                }
            } else {

                $params = [
                    'name' => $data['name'],
                    'video_url' => $video_url
                ];
                if ($id) {
                    $avatar = new FigureAvatar();
                    $avatarInfo = $avatar->where(['id' => $id])->find();
                    $params['_id'] = $avatarInfo['_id'];
                } else {
                    if (!$user['is_member']) {
                        $tally = sysconfig('tally', 'avatar_high_deduct');
                        if ($user['balance'] < $tally) {
                            return result(-2, '点数不足，请充值');
                        }
                    }
                }
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                    $result = $apiService->avatarStartTraining($params);
                } else {
                    $apiService = new ApiService();
                    $result = $apiService->avatarStartTraining($params);
                }
                if (isset($result['code']) && $result['code'] == 1) {
                    $avatar = new FigureAvatar();
                    if (empty($id)) {
                        $avatar->save($data);
                        user_balance_used($uid, $log_no, 2, 40);
                        $avatar->save([
                            '_id' => $result['data']['id'],
                            'current_status' => $result['data']['current_status']
                        ]);
                    } else {
                        $avatar->where(['id' => $id])->update([
                            '_id' => $result['data']['id'],
                            'current_status' => $result['data']['current_status']
                        ]);
                    }

                    return result(0, '上传成功', $avatar);
                } else {
                    return result(-1, $result['msg']);
                }
            }

        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象列表
     * http://aigc.weijuyunke.cn/mobile/avatar/avatarList
     *
     * @param
     *            uid 用户id
     * @param
     *            name 名称
     * @param
     *            page 页码
     * @param
     *            type 1-快速 2-高级
     * @param
     *            current_status 状态
     * @param
     *            psize 每页条数
     */
    public function avatarList()
    {
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));

            $where = " uid = {$uid}  AND current_status != '' ";

            if (!empty(input('name'))) {
                $name = input('name');
                $where .= " AND name LIKE '%{$name}%' ";
            }

            if (!empty(input('type'))) {
                $type = input('type');
                $where .= " AND type = {$type} ";
            }

            if (!empty(input('a_type'))) {
                $a_type = input('a_type');
                $where .= " AND a_type = {$a_type} ";
            }

            if (!empty(input('definition'))) {
                $definition = input('definition');
                $where .= " AND definition = {$definition} ";
            }


            /* if (!empty(input('current_status'))) {
                 $current_status = input('current_status');

                 if ($current_status == 'initialized') {
                     $where .= " AND (current_status = 'sent' OR current_status = 'initialized' OR current_status = 'processing') ";
                 } else {
                     $where .= " AND (current_status = '{$current_status}' or new_current_status = '{$current_status}')";
                 }
             }

             if (!empty(input('new_current_status'))) {
                 $new_current_status = input('new_current_status');
                 $where .= " AND new_current_status = '{$new_current_status}'";
             }*/
            /*if (!empty(input('current_status')) && !empty(input('new_current_status'))  && !empty(input('composite_current_status')) ) {
                $current_status = input('current_status');
                $new_current_status = input('new_current_status');
                $composite_current_status= input('composite_current_status');
                $where .= " AND (current_status = '{$current_status}' or new_current_status = '{$new_current_status}' or composite_current_status = '{$composite_current_status}' )";

            } else if (!empty(input('current_status')) && empty(input('new_current_status')) &&  empty(input('composite_current_status'))) {
                $current_status = input('current_status');
                $where .= " AND (current_status = '{$current_status}')";
            } else if (empty(input('current_status')) && !empty(input('new_current_status')) &&  empty(input('composite_current_status'))) {
                $new_current_status = input('new_current_status');
                $where .= " AND ( new_current_status = '{$new_current_status}')";
            } else if (empty(input('current_status')) && empty(input('new_current_status')) &&  !empty(input('composite_current_status'))) {
                $composite_current_status = input('composite_current_status');
                $where .= " AND ( composite_current_status = '{$composite_current_status}')";
            }*/
            if (!empty(input('current_status')) && !empty(input('new_current_status')) && !empty(input('composite_current_status')) && !empty(input('four_current_status'))) {
                $current_status = input('current_status');
                $new_current_status = input('new_current_status');
                $composite_current_status = input('composite_current_status');
                $four_current_status = input('four_current_status');

                $where .= " AND (current_status = '{$current_status}' or new_current_status = '{$new_current_status}' or composite_current_status = '{$composite_current_status}' or four_current_status ='{$four_current_status}'  )";

            } else {
                if (!empty(input('current_status'))) {
                    $current_status = input('current_status');
                    $where .= " AND (current_status = '{$current_status}')";
                }
                if (!empty(input('new_current_status'))) {
                    $current_status = input('new_current_status');
                    $where .= " AND (new_current_status = '{$current_status}')";
                }
                if (!empty(input('composite_current_status'))) {
                    $current_status = input('composite_current_status');
                    $where .= " AND (composite_current_status = '{$current_status}')";
                }
                if (!empty(input('four_current_status'))) {
                    $current_status = input('four_current_status');
                    $where .= " AND (four_current_status = '{$current_status}')";
                }
            }


            if (!empty(input('buy_expire'))) {
                $buy_expire = input('buy_expire');

                if ($buy_expire == '2') {
                    $where .= " AND (effective_time = '0' OR effective_time > " . time() . ") ";
                }
            }

            $total = FigureAvatar::where($where)->count();
            if ($total) {
                $list = FigureAvatar::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                foreach ($list as $key => $value) {

                    if ($value['effective_time'] > 0) {
                        if ($value['effective_time'] < time()) {
                            $list[$key]['buy_expire'] = '1';
                            $list[$key]['buy_expire_name'] = '已过期';
                        } else {
                            $list[$key]['buy_expire'] = '2';
                            $list[$key]['buy_expire_name'] = '未过期';
                        }
                        $list[$key]['effective_time'] = date('Y-m-d ', $value['effective_time']);
                    } else {
                        $list[$key]['buy_expire'] = '2';
                        $list[$key]['buy_expire_name'] = '永久';
                    }
                }

            } else {
                $list = array();
            }

            $totalPage = ceil($total / $psize);

            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象是否生成成功
     * http://aigc.weijuyunke.cn/mobile/avatar/avatarStatus
     *
     * @param
     *            uid 用户id
     * @param
     *            avatar_id 形象id
     */
    public function avatarStatus()
    {
        try {
            $uid = input('uid');
            $avatar_id = input('avatar_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $avatar = FigureAvatar::where([
                'uid' => $uid,
                'id' => $avatar_id
            ])->find();

            if (empty($avatar)) {
                return result(-1, '形象不存在');
            }

            if ($avatar == 'completed') {
                return result(0, 'success', 1);
            }

            $flag = 0;

            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
                $result = $apiService->avatarDetail($avatar['_id']);
            } else {
                $apiService = new ApiService();
                $result = $apiService->avatarDetail($avatar['_id']);
            }


            if (isset($result['code']) && $result['code'] == 1) {

                if (isset($result['data'])) {

                    $data = [
                        'new_current_status' => $result['data']['new_current_status'],
                    ];
                    if ($result['data']['current_status']) {
                        $data['current_status'] = $result['data']['current_status'];
                    }

                    $avatar->save($data);

                    if ($result['data']['current_status'] == 'completed' || $result['data']['new_current_status'] == 'completed') {
                        $flag = 1;
                    }
                }
            }

            return result(0, 'success', $flag);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 形象删除
     * http://aigc.weijuyunke.cn/mobile/avatar/avatarDel
     *
     * @param
     *            uid 用户id
     * @param
     *            avatar_id 形象id
     */
    public function avatarDel()
    {
        try {
            $uid = input('uid');
            $avatar_id = input('avatar_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $avatar = FigureAvatar::where([
                'uid' => $uid,
                'id' => $avatar_id
            ])->find();
            if (empty($avatar)) {
                return result(-1, '形象不存在');
            }

            $avatar->delete();
            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }


    public function allTraining()
    {
        try {
            $uid = input('uid');
            $set = FigureCloneSet::where("id", 1)->find();

            if ($set['avatar_high_open'] != 1 && $set['two_avatar_high_open'] != 1) {
                return result(0, '线路关闭');
            }
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $video_url = input('video_url');

            if (empty($video_url)) {
                return result(-1, 'video_url必传');
            }

            if (!$user['is_member']) {
                $tally = sysconfig('tally', 'avatar_high_deduct');

                if ($user['balance'] < $tally) {
                    return result(-2, '点数不足，请充值');
                }
            }

            $log_no = getPayNo('AT');
            $data = array(
                'log_no' => $log_no,
                'uid' => $uid,
                'a_type' => 1,
                'type' => 1,
                'is_avatar' => input('is_avatar'),
                'current_status' => 'nothing',
                'new_current_status' => 'nothing',

            );

            $data['name'] = !empty(input('name')) ? input('name') : date('ymd') . rand(999, 9999);

            if (!empty($video_url)) {

                $data['video_url'] = $video_url;

                $upload = sysconfig('upload');

                if ($upload['upload_type'] == 'alioss') {
                    $data['video_cover'] = $video_url . "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto";
                } elseif ($upload['upload_type'] == 'txcos') {
                    $data['video_cover'] = $video_url . "?ci-process=snapshot&time=0.01";
                } elseif ($upload['upload_type'] == 'qnoss') {
                    $data['video_cover'] = $video_url . "?vframe/jpg/offset/0";
                }
            }
            $is_avatar = input('is_avatar');

            if ($is_avatar && $is_avatar == 1) {// 分身数据不需要审核
                $params = [
                    'name' => $data['name'],
                    'video_url' => $video_url
                ];

                $avatar = new FigureAvatar();
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                } else {
                    $apiService = new ApiService();
                }
                $resultTwo = $result = ['code' => 1];
                if ($set['two_avatar_high_open'] == 1) {
                    $resultTwo = $apiService->StartTrainingTow($params);
                    if (isset($resultTwo['code']) && $resultTwo['code'] == 1) {
                        if ($set['avatar_high_open'] != 1) {
                            $avatar->save($data);
                        }
                        if (sysconfig('account', 'operation_version') == 2) {
                            $avatar->save([
                                '_id' => $resultTwo['data']['id'],
                                'new_current_status' => $resultTwo['data']['new_current_status'],
                            ]);
                        } else {
                            $avatar->save([
                                '_id' => $resultTwo['data']['id'],
                                'new_current_status' => $resultTwo['data']['current_status'],
                            ]);
                        }

                    }
                    return result(0, '成功', $avatar);
                }
                if ($resultTwo['code'] != 1) {
                    return result(-1, '失败');
                }
            } else {
                if (isset($set['avatar_high_check']) && $set['avatar_high_check'] == 1) {

                    $avatar = new FigureAvatar();
                    $avatar->save($data);
                    user_balance_used($uid, $log_no, 2, 40);
                    $avatar->save([
                        'is_status' => 1,
                        'current_status' => 'nothing',
                        'new_current_status' => 'nothing'
                    ]);
                    return result(0, '上传成功，等待审核', $avatar);
                } else {
                    $params = [
                        'name' => $data['name'],
                        'video_url' => $video_url
                    ];
                    $avatar = new FigureAvatar();
                    if (sysconfig('account', 'operation_version') == 2) {
                        $apiService = new AgentApiService();
                    } else {
                        $apiService = new ApiService();
                    }
                    $resultTwo = $result = ['code' => 1];
                    if ($set['avatar_high_open'] == 1) {
                        $result = $apiService->avatarStartTraining($params);

                        if (isset($result['code']) && $result['code'] == 1) {
                            $avatar->save($data);
                            user_balance_used($uid, $log_no, 2, 40);
                            $avatar->save([
                                '_id' => $result['data']['id'],
                                'current_status' => $result['data']['current_status'],
                            ]);
                            $params['_id'] = $result['data']['id'];
                        }
                    } else {
                        $result['code'] = 0;
                    }

                    if ($set['two_avatar_high_open'] == 1) {
                        $resultTwo = $apiService->StartTrainingTow($params);
                        if (isset($resultTwo['code']) && $resultTwo['code'] == 1) {
                            if ($result['code'] != 1) {
                                user_balance_used($uid, $log_no, 2, 40);
                                $avatar->save($data);
                            }
                            if (sysconfig('account', 'operation_version') == 2) {
                                $avatar->save([
                                    '_id' => $resultTwo['data']['id'],
                                    'new_current_status' => $resultTwo['data']['new_current_status'],
                                ]);
                            } else {
                                $avatar->save([
                                    '_id' => $resultTwo['data']['id'],
                                    'new_current_status' => $resultTwo['data']['current_status'],
                                ]);
                            }


                        }
                    } else {
                        $resultTwo['code'] = 0;
                    }
                    if ($resultTwo['code'] != 1 && $result['code'] != 1) {
                        return result(-1, '失败');
                    }
                }
            }
            return result(0, '上传成功', $avatar);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function towTraining()  // 重新提交不需要审核了
    {
        try {

            $set = FigureCloneSet::where("id", 1)->find();

            $uid = input('uid');
            $id = input('id');
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $video_url = input('video_url');
            if (empty($video_url)) {
                return result(-1, 'video_url必传');
            }
            $log_no = getPayNo('AT');
            $data = array(
                'log_no' => $log_no,
                'uid' => $uid,
                'a_type' => 1,
                'type' => 1,
                'is_avatar' => input('is_avatar')
            );
            $data['name'] = !empty(input('name')) ? input('name') : date('ymd') . rand(999, 9999);
            if (!empty($video_url)) {
                $data['video_url'] = $video_url;
                $upload = sysconfig('upload');

                if ($upload['upload_type'] == 'alioss') {
                    $data['video_cover'] = $video_url . "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto";
                } elseif ($upload['upload_type'] == 'txcos') {
                    $data['video_cover'] = $video_url . "?ci-process=snapshot&time=0.01";
                } elseif ($upload['upload_type'] == 'qnoss') {
                    $data['video_cover'] = $video_url . "?vframe/jpg/offset/0";
                }
            }
            $is_avatar = input('is_avatar');
            if ($is_avatar && $is_avatar == 1) {// 分身数据不需要审核
                if (!$user['is_member']) {
                    $tally = sysconfig('tally', 'avatar_high_deduct_two');
                    if ($user['balance'] < $tally) {
                        return result(-2, '点数不足，请充值');
                    }
                }
                $params = [
                    'name' => $data['name'],
                    'video_url' => $video_url
                    , 'way' => 3
                ];
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();
                    $params['is_avatar'] = input('is_avatar');

                } else {
                    $apiService = new ApiService();

                }
                $result = $apiService->StartTrainingTow($params);
                if (isset($result['code']) && $result['code'] == 1) {
                    $avatar = new FigureAvatar();
                    $avatar->save($data);
                    $FigureWayName = new \app\admin\model\FigureWayName();
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 2])
                        ->find();
                    user_balance_used($uid, $log_no, 2, 41, 1, $FigureWayNameInfo['reception'] . '形象克隆');


                    $data = $result['data'];
                    if (sysconfig('account', 'operation_version') == 2) {
                        $avatar->save([
                            '_id' => $data['id'],
                            'new_current_status' => $data['new_current_status']
                        ]);
                    } else {
                        $avatar->save([
                            '_id' => $data['id'],
                            'new_current_status' => $data['current_status']
                        ]);
                    }

                    return result(0, '上传成功', $avatar);
                } else {
                    return result(-1, $result['msg']);
                }
            } else {
                $params = [
                    'name' => $data['name'],
                    'video_url' => $video_url
                ];
                if ($id) {
                    $avatar = new FigureAvatar();
                    $avatarInfo = $avatar->where(['id' => $id])->find();
                    $params['_id'] = $avatarInfo['_id'];
                }
                if (sysconfig('account', 'operation_version') == 2) {
                    $apiService = new AgentApiService();

                } else {
                    $apiService = new ApiService();

                }
                $result = $apiService->StartTrainingTow($params);
                if (isset($result['code']) && $result['code'] == 1) {

                    $avatar = new FigureAvatar();
                    if (empty($id)) {
                        user_balance_used($uid, $log_no, 2, 40, 1, '线路二形象克隆');
                        $avatar->save($data);
                        $avatar->save([
                            '_id' => $result['data']['id'],
                            'new_current_status' => $result['data']['current_status']
                        ]);

                    } else {
                        $avatar->where(['id' => $id])->save([
                            '_id' => $result['data']['id'],
                            'new_current_status' => $result['data']['current_status']
                        ]);
                    }
                    return result(0, '上传成功', $avatar);
                } else {
                    return result(-1, $result['msg']);
                }
            }

        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }


    public function avatarClone()
    {
        try {

            $id = input('id');
            $way = input('way');
            $uid = input('uid');
            $user = FigureUser::where('id', $uid)->find();
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }
            $avatar = new FigureAvatar();
            $avatarInfo = $avatar->where(['id' => $id])->find();
            if (empty($avatarInfo)) {
                return result(-1, '形象不存在');
            }
            if ($way == 2) {
                if (!$user['is_member']) {
                    $tally = sysconfig('tally', 'avatar_high_deduct');
                    if ($user['balance'] < $tally) {
                        return result(-2, '点数不足，请充值');
                    }
                }
            } else if ($way == 3) {
                if (!$user['is_member']) {
                    $tally = sysconfig('tally', 'avatar_high_deduct_two');

                    if ($user['balance'] < $tally) {
                        return result(-2, '点数不足，请充值');
                    }
                }
            } else if ($way == 4) {
                if (!$user['is_member']) {
                    $tally = sysconfig('tally', 'avatar_deduct');
                    if ($user['balance'] < $tally) {
                        return result(-2, '点数不足，请充值');
                    }
                }
            } else if ($way == 5) {
                if (!$user['is_member']) {
                    $tally = sysconfig('tally', 'avatar_deduct_four');
                    if ($user['balance'] < $tally) {
                        return result(-2, '点数不足，请充值');
                    }
                }
            }
            $params = [
                'name' => $avatarInfo['name'],
                'way' => $way,
                'video_url' => $avatarInfo['video_url'],
                '_id' => $avatarInfo['_id']
            ];
            $result = $apiService->avatarClone($params);
            $FigureWayName = new \app\admin\model\FigureWayName();

            if (isset($result['code']) && $result['code'] == 1) {
                $avatar = new FigureAvatar();
                if ($way == 2) {
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 1])
                        ->find();
                    user_balance_used($uid, $avatarInfo['log_no'], 2, 40, 1, $FigureWayNameInfo['reception'] . '形象克隆');
                    $avatar->where(['id' => $id])->update([
                        '_id' => $result['data']['id'],
                        'current_status' => $result['data']['current_status']
                    ]);
                } elseif ($way == 3) {
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 2])
                        ->find();
                    user_balance_used($uid, $avatarInfo['log_no'], 2, 41, 1, $FigureWayNameInfo['reception'] . '形象克隆');

                    $avatar->where(['id' => $id])->update([
                        '_id' => $result['data']['id'],
                        'new_current_status' => $result['data']['current_status']
                    ]);
                } elseif ($way == 4) {
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 3])
                        ->find();
                    user_balance_used($uid, $avatarInfo['log_no'], 2, 42, 1, $FigureWayNameInfo['reception'] . '形象克隆');
                    $avatar->where(['id' => $id])->update([
                        '_id' => $result['data']['id'],
                        'composite_current_status' => $result['data']['current_status']
                    ]);
                } elseif ($way == 5) {
                    $FigureWayNameInfo = $FigureWayName
                        ->where(['id' => 4])
                        ->find();
                    user_balance_used($uid, $avatarInfo['log_no'], 2, 43, 1, $FigureWayNameInfo['reception'] . '形象克隆');
                    $avatar->where(['id' => $id])->update([
                        '_id' => $result['data']['id'],
                        'four_current_status' => $result['data']['current_status']
                    ]);
                }
                return result(0, '提交成功', $avatar);
            } else {
                return result(-1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function uploadAvatar()
    {
        $uid = input('uid');
        $video_url = input('video_url');
        $definition = input('definition'); //是否高清
        if (empty($video_url)) {
            return result(-1, '请上传视频链接');
        }
        $log_no = getPayNo('AT');
        $data = array(
            'log_no' => $log_no,
            'uid' => $uid,
            'a_type' => 1,
            'type' => 1,
            'composite_current_status' => 'nothing',
            'new_current_status' => 'nothing',
            'current_status' => 'nothing',
            'definition' => $definition
        );

        $data['name'] = !empty(input('name')) ? input('name') : date('ymd') . rand(999, 9999);
        $data['video_url'] = $video_url;
        $data['video_cover'] = $video_url . "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto";

//        if (sysconfig('upload', 'alioss_manage_endpoint') && sysconfig('upload', 'alioss_manage_name') ){
//

       /* }*/




        $avatar = new FigureAvatar();
        $set = FigureCloneSet::where("id", 1)->find();


        if (isset($set['avatar_check']) && $set['avatar_check'] == 1) {
            $data['is_status'] = 1;
        }elseif ($set['avatar_check'] == 3){
            $config = new \Darabonba\OpenApi\Models\Config([
                // 您的AccessKey ID
                "accessKeyId" => sysconfig('upload', 'alioss_access_key_id'),
                // 您的AccessKey Secret
                "accessKeySecret" => sysconfig('upload', 'alioss_access_key_secret'),
                'endpoint' => $set['alioss_manage_endpoint'],
            ]);
            $client = new Imm($config);
            $getProjectRequest = new GetProjectRequest([
                "projectName" => $set['alioss_manage_name']
            ]);
            $runtime = new RuntimeOptions([]);
            try {
                $client->getProjectWithOptions($getProjectRequest, $runtime);
            } catch (\Exception $exception) {
                return result(0, '请联系管理员查看智能媒体管理');
                /* if ($exception->getCode() == 'ResourceNotFound') {
                     try {
                         // 复制代码运行请自行打印 API 的返回值
                         $createProjectRequest = new CreateProjectRequest([
                             "projectName" => "avatar"
                         ]);
                         $client->createProjectWithOptions($createProjectRequest, $runtime);
                         try{
                             $detectImageFacesRequest = new DetectImageFacesRequest([
                                 "projectName" => "avatar",
                                 "sourceURI" => $video_url
                             ]);
                            $result =  $client->detectImageFacesWithOptions($detectImageFacesRequest, $runtime);
                            var_dump($result);
                         }catch (\Exception $ex){
                             echo $ex->getMessage().'111';exit;
                         }
                     }catch (\Exception $e) {
                         echo $e->getMessage().'222';exit;
                     }


                 } else {

                 }*/
            }
            $VideoPath = parse_url($video_url, PHP_URL_PATH);
            $videoFileName = basename($VideoPath);
            $path =  explode('.',$videoFileName);
            $videoDownloadPath = root_path() . 'public/' . $path[0].'.png';
            $ch = curl_init($data['video_cover']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            $videoData = curl_exec($ch);
            curl_close($ch);
            // 将视频数据保存到本地文件
            $videoFile = fopen($videoDownloadPath, 'wb');
            fwrite($videoFile, $videoData);
            fclose($videoFile);
            $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
            $uploadVideoUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'),  $path[0].'.png', $videoDownloadPath);
            // $png = $uploadVideoUrl['info']['url'];
            // 上传阿里云后删除
            unlink($videoDownloadPath);
            try {
                // oss://xweijuyunke/0007c0251539223bf8a01e0a0ee9f901.jpg
                $detectImageFacesRequest = new DetectImageFacesRequest([
                    "projectName" => $set['alioss_manage_name'] ,
                    "sourceURI" => 'oss://'. sysconfig('upload', 'alioss_bucket').'/'.$path[0].'.png'
                ]);
                $result =  $client->detectImageFacesWithOptions($detectImageFacesRequest, $runtime);
                if ( count($result->body->faces) !=  1){
                    return result(-1, '检测多个人脸');
                }
            } catch (\Exception $exception) {
                return result(-1, $exception->getMessage());

            }
        }

        $avatar->save($data);

        return result(0, '上传成功', $avatar);

    }


}